package com.mew.chess.core.game.pokdeng;

import com.mew.chess.core.common.handler.AbstractEnterExitHandler;
import com.mew.chess.core.common.handler.ChessEEAnnotation;
import com.mew.chess.core.game.pokdeng.game.*;
import com.mew.chess.core.game.pokdeng.game.common.PokDengPushCMDMapType;
import com.mew.chess.core.game.pokdeng.game.core.TableUtil;
import com.mew.chess.core.game.pokdeng.game.message.EnterResponse;
import com.mew.chess.core.game.pokdeng.game.message.UserMessage;
import com.mew.chess.core.game.shbz.game.ShbzGameManager;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.bo.GameSession;
import com.mew.common.rest.bo.MewSession;
import com.mew.common.rest.game.ChessEnterRoomResponse;
import com.mew.common.util.DateUtils;
import com.zebra.remoting.protocol.ZebraCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author dylin
 */
@ChessEEAnnotation("POKDENG")
@Service
@Slf4j
public class PokDengEEHandler extends AbstractEnterExitHandler {
    @Autowired
    private StartPokDengService startPokDengService;

    @Override
    public ResponseCode doSitDown(int roomId, GameSession chessSession, MewSession session, boolean isRepeat) {
        try {
            PokDengGameManager gameManager = PokDengGameManager.getInstance();
            //1 校验
            PokDengRoomManager roomManager = gameManager.getController(roomId);
            if (null == roomManager) {
                startPokDengService.initializeRoomManager(chessSession.getGameId(), roomId);
                roomManager = gameManager.getController(roomId);
                if (null == roomManager) {
                    log.error("POKDENG roomId {} is null", roomId);
                    return ResponseCode.SysException;
                }
            }
            //2 坐下 tableId,  seatNo
            PokDengSeatManager seatManager = backSeatCheck(roomManager, chessSession);
            UserMessage user;
            if (null == seatManager) {
                user = new UserMessage();
                user.setGameSession(chessSession);
                seatManager = entityRoomSitDown(roomManager, user);
            } else {
                user = seatManager.getUser();
            }

            if (null == seatManager) {
                log.error("EnterRoom RoomFull error: roomId {} , uid {}", chessSession.getRoomId(), chessSession.getUserId());
                return ResponseCode.SysException;
            }

            setData(chessSession, user);
            return ResponseCode.Success;
        }catch (Exception e){
            e.printStackTrace();
            return ResponseCode.SysException;
        }
    }

    @Override
    public void doFinish(GameSession chessSession, ZebraCommand command, ChessEnterRoomResponse enterRoomResponse) {

        PokDengTableManager tableManager=PokDengGameManager.getInstance().getController(chessSession.getRoomId()).getTableManager(chessSession.getTableId());
        PokDengSeatManager seatManager=tableManager.getPokDengSeatManager(chessSession.getSeatNo());
            tableManager.registerOnlineUser(chessSession);

        //2 当有一人坐下 游戏就开始
        if (!tableManager.checkIsNoStart()){
            tableManager.startGame();
        }
        //这个人的进入信息就推给其他人
        tableManager.pushUserEE(seatManager, PokDengPushCMDMapType.UserEnterRoom);

        EnterResponse responseMessage = new EnterResponse();
        responseMessage.setUserMessage(seatManager.getUser());
        responseMessage.setRoomBetArray(tableManager.getBetArrays());
        responseMessage.setLastBetNumber(enterRoomResponse.getLastBetNumber());

        responseMessage.setIno(tableManager.getIno());
        responseMessage.setTableId(tableManager.getTableId());
        responseMessage.setSeatNo(seatManager.getSeatNo());
        responseMessage.setStartSeat(tableManager.getAskStartSeat()+1);
        responseMessage.setBanker(tableManager.getBanker());
        responseMessage.setSeats(tableManager.getSeatMap().values());

        responseMessage.setLinkType(tableManager.getLinkType());
        responseMessage.setRemainTime(DateUtils.remainTimeMillis(tableManager.getStartTime() == 0 ? System.currentTimeMillis() : tableManager.getStartTime(), tableManager.getRuleTime()));

        command.setToken(chessSession.getTk());
        command.sendMessage(responseMessage);
    }

    @Override
    public boolean doExitRoom(MewSession session, int roomId) {
        if(!session.checkChessPlaying()){
            PokDengRoomManager roomManager=PokDengGameManager.getInstance().getController(roomId);
            roomManager.exitRoom(session.uid);
            return false;
        }
        return true;
    }
    private PokDengSeatManager backSeatCheck(PokDengRoomManager room,GameSession chessSession){
        if (null == chessSession||chessSession.getTableId()==0||chessSession.getSeatNo()==0){
            return null;
        }

        PokDengTableManager table = room.getTableManager(chessSession.getTableId());
        if (null == table){
            log.info("Reconnect table is null：roomInout {}", chessSession.toString());
            return null;
        }

        PokDengSeatManager seat = table.getPokDengSeatManager(chessSession.getSeatNo());
        if (null == seat){
            log.info("Reconnect seat is null：roomInout {}", chessSession.toString());
            return null;
        }
        if(null!=seat.getUser()&&seat.getUser().getUserId()!=chessSession.getUserId()){
            log.info("Reconnect seat has player：roomInout {}", chessSession.toString());
            return null;
        }
        if(null==seat.getUser()){
            log.info("Reconnect seat dont has player：roomInout {}", chessSession.toString());
            return null;
        }
        return seat;
    }
    private PokDengSeatManager entityRoomSitDown(PokDengRoomManager roomManager, UserMessage user){
        return TableUtil.entityRoomSitDownRecursion(roomManager, user);
    }

    private void setData(GameSession chessSession,UserMessage user){
        chessSession.setTableId(user.getTableId());
        chessSession.setSeatNo(user.getSeatNo());
    }
}
